package com.util;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonUtil {
	private static Gson gson = new Gson();

	public static String objectToStr(Object obj) {
		return objectToStr(obj, null);
	}

	public static String objectToStr(Object obj, final String[] excludeProperty) {
		String jsonStr = null;
		try {
			if (obj != null) {
				if (excludeProperty == null || excludeProperty.length == 0) {
					jsonStr = gson.toJson(obj);
				} else {
					gson = new GsonBuilder().setExclusionStrategies(
							new ExclusionStrategy() {

								public boolean shouldSkipClass(Class<?> arg0) {
									// TODO Auto-generated method stub
									return false;
								}

								public boolean shouldSkipField(
										FieldAttributes fieldAttributes) {
									for (String str : excludeProperty) {
										if (fieldAttributes.getName()
												.equalsIgnoreCase(str)) {
											return true;
										}
									}
									return false;
								}
							}).create();
					jsonStr = gson.toJson(obj);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(jsonStr);
		return jsonStr;
	}
	public static void jsonOut(Object obj) {
		BaseActionUtil.out.print(objectToStr(obj));
		BaseActionUtil.out.flush();
		BaseActionUtil.out.close();
	}

	public static void jsonOut(Object obj, final String[] excludeProperty) {
		BaseActionUtil.out.print(objectToStr(obj, excludeProperty));
		BaseActionUtil.out.flush();
		BaseActionUtil.out.close();
	}
}
